package com.gzw.dms.map;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MapViewLayoutParams;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.google.gson.reflect.TypeToken;
import com.gzw.dms.MyApplication;
import com.gzw.dms.R;
import com.gzw.dms.base.BaseActivity;
import com.gzw.dms.bean.MapInfo;
import com.gzw.dms.bean.UserInfo;
import com.gzw.dms.utils.DateUtil;
import com.gzw.dms.utils.HttpUtils;
import com.gzw.dms.utils.JsonUtil;
import com.gzw.dms.utils.L;
import com.gzw.dms.utils.T;
import com.gzw.dms.utils.UrlUtils;
import com.summerxia.dateselector.widget.DateTimeSelectorDialogBuilder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class MapActivity extends BaseActivity {
    private BaiduMap mBaiduMap;
    private String tag = "MapActivity-->";
    private Context mContext;
    private MapInfo driverInfo;
    private String beidouid;
    private String nowspace;
    private String state;
    private String newtime = DateUtil.getToday();
    private String yesterday = DateUtil.getYesterday();
    private String start = yesterday + ":00";
    private String over = newtime + ":00";
    private String starPage = "0";
    private String page = "0";

    private TextView tv_map_gpsstate , tv_map_carno , tv_map_departmentname , tv_map_nowdate ,
            tv_map_nowspace , tv_item_dialog_start , tv_item_dialog_over , tv_item_dialog_hint;
    private DateTimeSelectorDialogBuilder dateSelectorStart , dateSelectorOver;
    private Toolbar toolbar;
    private List<MapInfo> lsMapInfo = new ArrayList<>();
    private Marker marker;
    private boolean isTrafficEnabled = false;
    private Handler myHandler;
    private boolean isOpenGjhf = false;//轨迹回放是否打开
    private boolean isRefreshLocation = false;//轨迹回放是是否能实时定位
    private int i = 0;
    private Thread thread;
    private Polyline mPolyline;
    private MapInfo mapInfo;
    private ImageButton ibtnLukuang;
    private Handler getXYHandler;
    private AlertDialog dialog;
    private View pb;
    private View popwindow;
    private boolean isOpenTherad = true;
    private GeoCoder mSearch = null; // 搜索模块
    MapView mMapView = null;
    private LatLng cenpt;
    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

    }

    @Override
    protected void setContentView() {
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_map);

    }

    @Override
    protected void initViews() {
        mMapView = (MapView) findViewById(R.id.bmapView);
        pb = findViewById(R.id.include_pb);
        toolbar = (Toolbar) findViewById(R.id.toolbar);

    }

    @Override
    protected void initData() {
        mContext = this;
        Intent intent = getIntent();
        driverInfo = (MapInfo) intent.getExtras().get(
                "driverInfo");
        toolbar.setTitle("地图");
        setSupportActionBar(toolbar);
        mBaiduMap = mMapView.getMap();
        myHandler = new MyHandler();
        getXYHandler = new GetXYHandler();
        thread = new Thread(new MThread());
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (isOpenTherad) {
                    try {
                        getXYHandler.sendEmptyMessage(1);
                        Thread.sleep(40 * 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    @Override
    protected void initEvents() {
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
//                moveTaskToBack(true);
            }
        });
//        ibtnLukuang.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (isTrafficEnabled) {
//                    mBaiduMap.setTrafficEnabled(false);
//                    isTrafficEnabled = false;
//                } else {
//                    mBaiduMap.setTrafficEnabled(true);//显示实时交通图
//                    isTrafficEnabled = true;
//                }
//            }
//        });
        //单机地图时响应
//        mBaiduMap.setOnMapClickListener(new MyMapClick());
    }


    class GetXYHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            L.e(tag, "GetXYHandler isRefreshLocation:" + isRefreshLocation);
            // 此处可以更新UI
            if (isRefreshLocation) {
                return;
            }
            ShowOrderTask showOrderTask = new ShowOrderTask();
            showOrderTask.execute();
        }
    }

    // 菜单项被选择事件
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.item_huifang:
                isOpenGjhf = true;
                if (thread.getState() == Thread.State.NEW) {
                    thread.start();
                }
                break;
            case R.id.item_zhanting:
                isOpenGjhf = false;
                break;
            case R.id.item_reviewforhour:
                i = 0;
                showDialog();
                isOpenGjhf = false;
                isRefreshLocation = true;
                if (mPolyline != null) {
                    mPolyline.remove();
                }
                break;


        }
        return super.onOptionsItemSelected(item);
    }


    /**
     * 作用 ：获取当前车辆的位置信息并显示在地图中间
     * @return
     * @params
     */
    public class ShowOrderTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            pb.setVisibility(View.VISIBLE);


        }

        protected String doInBackground(String... params) {
            Map<String, Object> map = new HashMap<>();
            UserInfo userInfo = MyApplication.getUserInfo();
            map.put("userInfo", userInfo);
            map.put("userName", driverInfo.getCarid());

            String json = JsonUtil.toJson(map);
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("getMapInfoByUserInfo"), "json=" + json);
        }

        @Override
        protected void onPostExecute(final String result) {
            pb.setVisibility(View.GONE);

            if (isNull(result)) {
                T.showShort(mContext, "连接服务器异常");
            } else {
                if (result.indexOf("errorMsg") > 0) {
                    String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                    T.showShort(mContext, errorMsg);
                } else if (result.indexOf("successMsg") > 0) {
                    String successMsg = JsonUtil.getMsg(result, "successMsg");
                    List<MapInfo> lsMapInfo;
                    lsMapInfo = (JsonUtil.getPersons(successMsg, new TypeToken<List<MapInfo>>() {
                    }.getType()));
                    if (lsMapInfo.size() != 0) {
                        mapInfo = lsMapInfo.get(0);
                        cenpt = new LatLng(Double.parseDouble(mapInfo.getLat()),
                                Double.parseDouble(mapInfo.getLng()));//获取坐标
//                        float angle = Float.parseFloat(mapInfo.getAngle());
//                        float gpsstate = Float.parseFloat(mapInfo.getGpsstate());
                        state = "1";
                        setMapStatus(cenpt);
                        getGeocode(cenpt);//根据最表获取地理位置
                        beidouid = mapInfo.getBeidouid();
                    }
                }
            }
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_map, menu);
        return true;
    }


    public class getNumber extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            pb.setVisibility(View.VISIBLE);

        }

        protected String doInBackground(String... params) {
            Map<String, Object> map = new HashMap<>();
//            UserInfo userInfo = MyApplication.getUserInfo();
//            map.put("userInfo", userInfo);
            map.put("userName", driverInfo.getCarid());
            map.put("startTime", params[0]);
            map.put("endTime", params[1]);

            String json = JsonUtil.toJson(map);
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("getPlayBackPageCount"), "json=" + json);
        }

        @Override
        protected void onPostExecute(final String result) {
            pb.setVisibility(View.GONE);

            if (isNull(result)) {
                T.showShort(mContext, "连接服务器异常");
            } else {
                if (result.indexOf("errorMsg") > 0) {
                    String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                    T.showShort(mContext, errorMsg);
                } else if (result.indexOf("successMsg") > 0) {
                    Log.e(tag, "onSuccess" + result);
                    String successMsg = JsonUtil.getMsg(result, "successMsg");
                    int num = Integer.parseInt(successMsg);
                    double n = num/1000;
                    int index = (int)Math.ceil(n);
                    page = String.valueOf(index);
                    getXYTime showOrderTask = new getXYTime();
                    showOrderTask.execute(start , over,starPage,page);

                }
            }
        }
    }

    public class getXYTime extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            pb.setVisibility(View.VISIBLE);

        }

        protected String doInBackground(String... params) {
            Map<String, Object> map = new HashMap<>();
            UserInfo userInfo = MyApplication.getUserInfo();
            map.put("userInfo", userInfo);
            map.put("userName", driverInfo.getCarid());
            map.put("startTime", params[0]);
            map.put("endTime", params[1]);
            map.put("page", params[2]);

            String json = JsonUtil.toJson(map);
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("getPlayBackPageMapInfo"), "json=" + json);
        }

        @Override
        protected void onPostExecute(final String result) {
            pb.setVisibility(View.GONE);

            if (isNull(result)) {
                T.showShort(mContext, "连接服务器异常");
            } else {
                if (result.indexOf("errorMsg") > 0) {
                    String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                    T.showShort(mContext, errorMsg);
                } else if (result.indexOf("successMsg") > 0) {
                    Log.e(tag, "onSuccess" + result);
                    String successMsg = JsonUtil.getMsg(result, "successMsg");
                    final List<MapInfo> lsMap = JsonUtil.getPersons(successMsg, new TypeToken<List<MapInfo>>() {
                    }.getType());
                    lsMapInfo.addAll(lsMap);

                    int starpage = Integer.parseInt(starPage);
                    int page1 = Integer.parseInt(page);
                    if (starpage == page1-1 || page1<=0){
                        addCustomElementsDemo(lsMapInfo);
                        return;
                    }else {
                        starpage++;
                        starPage = String.valueOf(starpage);
                        getXYTime showOrderTask = new getXYTime();
                        showOrderTask.execute(start , over,starPage,page);
                    }


                }
            }
        }
    }


    class MyHandler extends Handler {
        // 子类必须重写此方法，接受数据
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // 此处可以更新UI
            popwindow.setVisibility(View.GONE);
            Bundle bundle = msg.getData();
            MapInfo mapInfo = (MapInfo) bundle.getSerializable("mapInfo");
            //中心点坐标
            LatLng cenpt = new LatLng(Double.parseDouble(mapInfo.getLat()), Double.parseDouble(mapInfo.getLng()));
            if (mapInfo == lsMapInfo.get(0)) {
                setMapStatus(cenpt);
            }
            setDian(cenpt, mapInfo);
        }
    }

    class MThread implements Runnable {
        public void run() {
            L.e(tag, "gjhf-->run-->name:" + Thread.currentThread().getName() + "-->id:" + Thread.currentThread().getId());
            if (lsMapInfo == null || lsMapInfo.size() == 0) {
                return;
            }
            MapInfo mapInfo;
            while (isOpenTherad) {
                if (isOpenGjhf) {
                    if (i < lsMapInfo.size()) {
                        mapInfo = lsMapInfo.get(i);
                    } else {
                        return;
                    }

                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Message msg = new Message();
                    Bundle mBundle = new Bundle();
                    mBundle.putSerializable("mapInfo", mapInfo);
                    msg.setData(mBundle);
                    myHandler.sendMessage(msg);
                    i++;
                }
            }
        }
    }

    /**
     * 添加点、线、多边形、圆、文字
     */
    public void addCustomElementsDemo(List<MapInfo> lsMapInfo) {
        if (lsMapInfo == null || lsMapInfo.size() == 0) {
            T.showShort(mContext, "没有查到轨迹信息。");
            return;
        }
        LatLng latLng = new LatLng(Double.parseDouble(lsMapInfo.get(0).getLat()), Double.parseDouble(lsMapInfo.get(0).getLng()));

        MapInfo mapInfo1 = lsMapInfo.get(0);
        setMapStatus(latLng);

        setDian(latLng, mapInfo1);
        List<LatLng> points = new ArrayList<LatLng>();
        for (MapInfo mapInfo : lsMapInfo) {
            points.add(new LatLng(Double.parseDouble(mapInfo.getLat()), Double.parseDouble(mapInfo.getLng())));
        }
        OverlayOptions ooPolyline = new PolylineOptions().width(5)
                .color(0xAAFF0000).points(points);
        mPolyline = (Polyline) mBaiduMap.addOverlay(ooPolyline);
    }
    /**
     * 作用 ：设置地图状态
     * @return
     * @params cenpt ：中心点坐标
     */
    private void setMapStatus(LatLng cenpt) {
        // 定义地图状态
        MapStatus mMapStatus = new MapStatus.Builder().target(cenpt).zoom(15)
                .build();
        // 定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory
                .newMapStatus(mMapStatus);
        // 改变地图状态
        mBaiduMap.setMapStatus(mMapStatusUpdate);
    }

    private void addDian(LatLng cenpt , MapInfo Info) {

//        float angle = Float.parseFloat(Info.getAngle());
        final String Gpsstate = Info.getGpsstate().toString().trim();
        final String carno = Info.getCarno().toString().trim();
        final String nowdate = Info.getNowdate().toString().trim();
        final String deptname = Info.getDeptname().toString().trim();


        final Resources resources = getResources();
        getGeocode(cenpt);//根据最表获取地理位置
        //构建Marker图标
//        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.jiantou_shang);
//        OverlayOptions option = new MarkerOptions()
//                .position(cenpt)
//                .icon(bitmap)
//                .rotate(angle);
        MarkerOptions options = new MarkerOptions();
        options.position(cenpt);
//        options.rotate(angle);
//        if (state.equals("2")) {
//            options.icon(BitmapDescriptorFactory.fromResource(R.drawable.notification_type_flameout));
//        } else if (state.equals("3")) {
//            options.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_notification_delete));
//        } else {
        options.icon(BitmapDescriptorFactory.fromResource(R.mipmap.jiantou_shang));
//        }
        OverlayOptions option = options;

        //在地图上添加Marker，并显示
        if (marker != null) {
            marker.remove();
//            popwindow.setVisibility(View.GONE);
        }
        marker = (Marker) mBaiduMap.addOverlay(option);

        if (popwindow == null) {
            initPop(marker);
            MapViewLayoutParams params = new MapViewLayoutParams.Builder()
                    .width(MapViewLayoutParams.WRAP_CONTENT)
                    .height(MapViewLayoutParams.WRAP_CONTENT)
                    .position(marker.getPosition())//popwindow的坐标，不能为null，必须有
                    .layoutMode(MapViewLayoutParams.ELayoutMode.mapMode)
                    .yOffset(-5)
                    .build();

            mMapView.updateViewLayout(popwindow, params);
            popwindow.setVisibility(View.VISIBLE);

            tv_map_gpsstate.setText("定位来源:" + String.valueOf(Gpsstate) );
                tv_map_carno.setText("用户名:" + carno);
                tv_map_departmentname.setText("所属机构：" + deptname);
            tv_map_nowdate.setText(resources.getString(R.string.map_nowdate) + nowdate);
            tv_map_nowspace.setText(resources.getString(R.string.map_nowspace) + nowspace);
        }else {

        }

        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {

            @Override
            public boolean onMarkerClick(Marker marker) {

                MapViewLayoutParams params = new MapViewLayoutParams.Builder()
                        .width(MapViewLayoutParams.WRAP_CONTENT)
                        .height(MapViewLayoutParams.WRAP_CONTENT)
                        .position(marker.getPosition())//popwindow的坐标，不能为null，必须有
                        .layoutMode(MapViewLayoutParams.ELayoutMode.mapMode)
                        .yOffset(-5)
                        .build();

                mMapView.updateViewLayout(popwindow, params);
                popwindow.setVisibility(View.VISIBLE);

                tv_map_gpsstate.setText("定位来源:" + String.valueOf(Gpsstate) );
                tv_map_carno.setText("用户名:" + carno);
                tv_map_departmentname.setText("所属机构：" + deptname);
                tv_map_nowdate.setText(resources.getString(R.string.map_nowdate) + nowdate);
                tv_map_nowspace.setText(resources.getString(R.string.map_nowspace) + nowspace);
                return true;
            }
        });

        if (popwindow != null) {
            tv_map_gpsstate.setText("定位来源:" + String.valueOf(Gpsstate) );
            tv_map_carno.setText("用户名:" + carno);
            tv_map_departmentname.setText("所属机构：" + deptname);
            tv_map_nowdate.setText(resources.getString(R.string.map_nowdate) + nowdate);
            tv_map_nowspace.setText(resources.getString(R.string.map_nowspace) + nowspace);
        }
    }
    /**
     * 作用 ：设置目标车辆当前定位所在点
     * @return
     * @params cenpt ：目标车辆当前坐标
     */
    private void setDian(LatLng cenpt , MapInfo mapInfo) {
        if (!isOpenGjhf) {
            addDian(cenpt , mapInfo);
        }
        try {
//            float angle = 360 - Float.parseFloat(mapInfo.getAngle());
            getGeocode(cenpt);
            //        构建Marker图标

            BitmapDescriptor bitmap = BitmapDescriptorFactory
                    .fromResource(R.mipmap.jiantou_shang);
            OverlayOptions option = new MarkerOptions()
                    .position(cenpt)//点所在的坐标
                    .icon(bitmap)
                    .rotate(0);


            //在地图上添加Marker，并显示
            if (marker != null) {
                marker.remove();
            }
            marker = (Marker) mBaiduMap.addOverlay(option);


            //定义地图状态
            MapStatus mMapStatus = new MapStatus.Builder()
                    .target(cenpt)
                    .build();
            //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
            MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
            //改变地图状态

            mBaiduMap.setMapStatus(mMapStatusUpdate);
        } catch (Exception e) {
            L.e(tag, "Exception:" + e.getMessage());
        }
    }
    private class MyMapClick implements BaiduMap.OnMapClickListener {
        @Override
        public void onMapClick(LatLng latLng) {
            if (popwindow != null){
                popwindow.setVisibility(View.GONE);
            }
        }

        @Override
        public boolean onMapPoiClick(MapPoi mapPoi) {
            return false;
        }
    }

    /**
     * 点击出现时间选择器
     */
    public class MyClick implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            switch(v.getId()) {
                case R.id.tv_item_dialog_start:
                    if (dateSelectorStart == null) {
                        dateSelectorStart = DateTimeSelectorDialogBuilder.getInstance(mContext);
                        dateSelectorStart.setOnSaveListener(new DateTimeSelectorDialogBuilder.OnSaveListener() {
                            @Override
                            public void onSaveSelectedDate(String selectedDate) {
                                tv_item_dialog_start.setText(selectedDate);
                                start = selectedDate;
                                try {
                                    String result = DateUtil.dateCompare(start , over);
                                    Log.e(tag,"time ====" + result);
                                    //获取到alertdialog的确定按钮
                                    Button button = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
                                    if (result == "Wone") {
                                        tv_item_dialog_hint.setText("时间格式不正确");
                                        tv_item_dialog_hint.setBackgroundColor(Color.parseColor("#FF595A"));
                                        button.setEnabled(false);
                                    } else if (result == "Wtwo") {
                                        tv_item_dialog_hint.setText("请勿超过7天");
                                        tv_item_dialog_hint.setBackgroundColor(Color.parseColor("#FF595A"));
                                        button.setEnabled(false);
                                    } else {
                                        tv_item_dialog_hint.setText(result);
                                        tv_item_dialog_hint.setBackgroundColor(Color.parseColor("#3598da"));
                                        button.setEnabled(true);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                    dateSelectorStart.show();
                    break;
                case R.id.tv_item_dialog_over:
                    if (dateSelectorOver == null) {
                        dateSelectorOver = DateTimeSelectorDialogBuilder.getInstance(mContext);
                        dateSelectorOver.setOnSaveListener( new DateTimeSelectorDialogBuilder.OnSaveListener() {
                            @Override
                            public void onSaveSelectedDate(String selectedDate) {
                                tv_item_dialog_over.setText(selectedDate);
                                over = selectedDate;
                                try {
                                    String result = DateUtil.dateCompare(start , over);
                                    Log.e(tag,"time ====" + result);
                                    Button button = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
                                    if (result == "Wone") {
                                        tv_item_dialog_hint.setText("时间格式不正确");
                                        tv_item_dialog_hint.setBackgroundColor(Color.parseColor("#FF595A"));
                                        button.setEnabled(false);
                                    } else if (result == "Wtwo") {
                                        tv_item_dialog_hint.setText("请勿超过7天");
                                        tv_item_dialog_hint.setBackgroundColor(Color.parseColor("#FF595A"));
                                        button.setEnabled(false);
                                    } else {
                                        tv_item_dialog_hint.setText(result);
                                        tv_item_dialog_hint.setBackgroundColor(Color.parseColor("#3598da"));
                                        button.setEnabled(true);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                    dateSelectorOver.show();
                    break;
            }
        }
    }


    /**
     * 初始化popwindow
     * @param marker
     */
    private void initPop(Marker marker) {
        popwindow = View.inflate(mContext , R.layout.item_map_popwindow , null);
        tv_map_gpsstate = (TextView) popwindow.findViewById(R.id.tv_map_gpsstate);
        tv_map_carno = (TextView) popwindow.findViewById(R.id.tv_map_carno);
        tv_map_departmentname = (TextView) popwindow.findViewById(R.id.tv_map_departmentname);
        tv_map_nowdate = (TextView) popwindow.findViewById(R.id.tv_map_nowdate);
        tv_map_nowspace = (TextView) popwindow.findViewById(R.id.tv_map_nowspace);

        MapViewLayoutParams params = new MapViewLayoutParams.Builder()
                .width(MapViewLayoutParams.WRAP_CONTENT)
                .height(MapViewLayoutParams.WRAP_CONTENT)
                .position(marker.getPosition())//popwindow的坐标，不能为null，必须有
                .layoutMode(MapViewLayoutParams.ELayoutMode.mapMode)
                .build();

        mMapView.addView(popwindow, params);

        popwindow.setVisibility(View.GONE);//popwindow设置为隐藏
    }


    @SuppressLint("InflateParams")
    public void showDialog() {
        LayoutInflater inflater = getLayoutInflater();
        final View layout = inflater.inflate(R.layout.item_dialog_huifang, null);
        tv_item_dialog_hint = (TextView) layout.findViewById(R.id.tv_item_dialog_hint);
        tv_item_dialog_start = (TextView) layout.findViewById(R.id.tv_item_dialog_start);
        tv_item_dialog_over = (TextView) layout.findViewById(R.id.tv_item_dialog_over);

        tv_item_dialog_start.setText(yesterday + ":00");
        tv_item_dialog_over.setText(newtime + ":00");
        tv_item_dialog_start.setOnClickListener(new MyClick());
        tv_item_dialog_over.setOnClickListener(new MyClick());

        dialog = new AlertDialog.Builder(this).setTitle("请选择回放时间段").setView(layout)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        getXYTime showOrderTask = new getXYTime();
//                        showOrderTask.execute(start , over);
                        getNumber getNumber = new getNumber();
                        getNumber.execute(start , over);
                    }
                })
                .setNegativeButton("取消", null).show() ;
    }


    // 初始化搜索模块，注册事件监听
    public void getGeocode(LatLng cenpt) {
        mSearch = GeoCoder.newInstance();

        mSearch.setOnGetGeoCodeResultListener(new MyGeocoder());

        // 反Geo搜索
        mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(cenpt));

    }

    public class MyGeocoder implements OnGetGeoCoderResultListener {

        @Override
        public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

        }

        @Override
        public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
            if (reverseGeoCodeResult == null || reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR){
                T.showShort(MapActivity.this, "没有找到位置");
            } else {
                nowspace = reverseGeoCodeResult.getAddress().toString();
                if (state.equals("1")){
                    addDian(cenpt, mapInfo);
                    state = "2";
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        mMapView.onDestroy();
        mMapView=null;
        super.onDestroy();
        L.i(tag, "onDestroy():");
        L.i(tag, "onDestroy():" + lsMapInfo);
        L.i(tag, "onDestroy():" + i);
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
    }

    @Override
    protected void onResume() {
        super.onResume();
        L.i(tag, "onResume():");
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        L.i(tag, "onPause()");
        isOpenTherad = false;
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }


}
